import React, { useState, useEffect, useRef } from 'react';
import { useRequest, useModel } from 'umi';
import { Row, List, Card, Tabs, Descriptions, Image, message,Collapse,Radio,Space,Tooltip } from 'antd';
import { getMonitoringDevicInfo, getEChartsOption, getMonitoringPhase,getDesignMonitoringPhase } from '@/services/deviceLive';
 import GridLayout from 'react-grid-layout';
import { Responsive, WidthProvider } from 'react-grid-layout';

const ResponsiveGridLayout = WidthProvider(Responsive);


import moment from 'moment'
import ECharts from 'echarts-for-react';


import {alarmcode} from '@/utils/alarmcode-enum';
import AlarmTable from '@/pages/monitoring/deviceAlarm';
import { queryDeviceAlarm} from '@/services/sysDeviceAlarm';


import styles from './index.less';


import slg from '@/assets/img/img/slg.png';



const details: React.FC = (props: any) => {
 // const { params } = props.match;
  const params= {id:80000002}
  const second = useRequest(() => {
    return getDesignMonitoringPhase({...params,deviceType:1});
  }, {
    pollingInterval: 3000,
    pollingWhenHidden: false
  });



  const [deviceInfo, setDeviceInfo] = useState<API.DeviceItem>({});
  const [runningData, setRunningData] = useState({});

  const [chartIndex, setChartIndex] = useState(0);

  const [onLineBackgroundColor, setOnLineBackgroundColor] = useState('#8ca1aa');
  const [alarmBackgroundColor, setAlarmBackgroundColor] = useState('#8ca1aa');
  const [tripBackgroundColor, setTripBackgroundColor] = useState('#8ca1aa');

  const [designAttrList, setDesignAttrlist] = useState([]);
  const [designStateList, setDesignStatelist] = useState([]);
  const [attrLayout, setAttrLayout] = useState([])
  const [stateLayout, setStateLayout] = useState([])
  const [items, setItems] = useState([]);

  const [alarmlist, setAlarmlist] = useState<API.SysDeviceAttrItem[]>([]);

  const { initialState,setInitialState } = useModel('@@initialState');
  const { mySocket,dicts,currentUser } = initialState || {};
 

  if (mySocket) {
    mySocket.send(params.id);
    mySocket.onmessage =async function (e) {
     // console.log(`onmessage: ${e.data}`);
      //排除心跳数据
    if ("heartbeat" != e.data&&e.data.indexOf("AlarmData")!=-1) {
        const data = JSON.parse(e.data);
        await setInitialState((s) => ({ ...s, alarmNotices: data.AlarmData }));
      }else  if("heartbeat" != e.data){
        onMessage(e);
      }
    };
  }

  const onMessage = (e:any) => {
   

    const message = JSON.parse(e.data);
   // const runningData = {...message.RunningData, ...message.ReliabilityData}
    const rData = message.RunningData||{};
    console.log(rData)

    if(rData.deviceId!=params.id){
      return;
     }
    // console.log(rData)
    rData.acquisitionTime = moment().format("YYYY-MM-DD HH:mm:ss");
    if(runningData?.online==0&&rData?.online==1){
       go();
    }
    if(runningData?.alarm==0&&rData?.alarm==1){
        go1();
    }
    if(runningData?.trip==0&&rData?.trip==1){
        go2();
    }
    setRunningData(rData);
  }
  function compare(key){
    return function(value1,value2){
        var val1=value1[key];
        var val2=value2[key];
        return val1-val2;
    }
}

const formatStateList = async (template) =>  {
  let  stateLayouts=template?.stateLayout;
  let  stateLists=template?.stateList;
  stateLists.forEach(function(val,index){
      val.x=stateLayouts[index].x;
  })
  stateLists.sort(compare('x'));
  let newstateList=[];
  let states=new Array();
  stateLists.forEach(function(val,index){
    if(index>0&&val.x-stateLists[index-1].x>2){
      newstateList.push(states);
      states=new Array();
    }
    states.push(val);
  })
  newstateList.push(states);
  setDesignStatelist(newstateList);
}


const formatAttrList = async (template) =>  {
  let  attrLayouts=template?.attrLayout;
  let  attrLists=template?.attrList;
  attrLists.forEach(function(val,index){
      val.x=attrLayouts[index].x;
      val.y=attrLayouts[index].y;
  })
  attrLists.sort(compare('y'));
  console.log(attrLists)
  // let newstateList=[];
  // let states=new Array();
  // attrLists.forEach(function(val,index){
  //   if(index>0&&val.x-attrLists[index-1].x>2){
  //     newstateList.push(states);
  //     states=new Array();
  //   }
  //   states.push(val);
  // })
  // newstateList.push(states);
  // setDesignStatelist(newstateList);
}


  useEffect(() => {
    const setSelectData = async () => {
      var details = await getMonitoringDevicInfo(params);

      setRunningData(details.runningData||{});
      setDeviceInfo(details.deviceInfo);
      var alarms = await queryDeviceAlarm({"deviceId":params.id,"deviceTypeId":1});
      
      setAlarmlist(alarms);
      let template=localStorage.getItem("template");
      console.log(template)
      if(template!=null){
        template=JSON.parse(template);
        console.log(template)
        console.log(template?.attrList)
        console.log(template?.attrLayout)
        formatStateList(template);
        // formatAttrList(template);
 
        setItems(template?.tabitem);
        setAttrLayout(template?.attrLayout||[]);
        setDesignAttrlist(template?.attrList);
       
      }



      if(details.runningData?.online==1){
        await go();
      }
      if(details.runningData?.alarm==1){
        await  go1();
      }
      if(details.runningData?.trip==1){
        await  go2();
      }
    }
    setSelectData();
 
  }, []);

  const sleep = (t) => {
    return new Promise((res,rej)=>{
        setTimeout(res,t)
    })
}

  async function  go() {
    setOnLineBackgroundColor("yellow");
    await sleep(200)
    setOnLineBackgroundColor("#19377f");
    await  sleep(200)
    go()
}


async function  go1() {
  setAlarmBackgroundColor("red");
  await sleep(300)
  setAlarmBackgroundColor("#19377f");
  await  sleep(300)
  go1()
}
async function  go2() {
  setTripBackgroundColor("red");
  await sleep(300)
  setTripBackgroundColor("#19377f");
  await  sleep(300)
  go2()
}


const designItem = (item,index) => {
  // console.log(index)
  var url = null;
  let key=item.i+"";
  // console.log(key)
  switch (item.key) {
    case 1:
      url = (
        <div  key={key} className={styles.dataItem}  data-grid={{...attrLayout[index], static: true}}>
   
         <div className={styles.flexBetween}><Image  width={20}  height={20}  src={'/img/'  + item.picCode}  preview={false} /> <span className={styles.topRight} ></span></div>
         <div className={styles.middleValue}><span className={styles.data} >{runningData[item.filed]||'--' }</span><span className={styles.unit}>{item.unit}</span></div>
         <div className={styles.attribute}>{item.text}</div>
       </div>
      );
      break;
    case 2:
      url = (
        <div    key={key}  className={styles.dataItem}   data-grid={{...attrLayout[index], static: true}}>
        
          <div className={styles.flexBetween}><Image  width={20}  height={20}  src={'/img/'  + item.picCode}  preview={false} /> <span className={styles.topRight} ></span></div>
          <div> 
          {item.fileds.map((filed ,filedindex) => (
             <div style={{margin: '10px 0 10px 10px',color:'rgb(64 255 255)'}}  className={styles.flex}><span >{filed?.abb}</span>
             <div className={styles.dataBox} ><span className={styles.data1} >{runningData[filed.filed]||'--' }</span>{item.unit}</div></div>
            ))}
           
          </div>
          <div className={styles.attribute} style={{marginTop:'10px'}}>{item.text}</div>
        </div>
      );
      break;
    case 3:
        url = (  
        <div  key={key} className={styles.dataItem}   data-grid={{...attrLayout[index], static: true}}>
         
        <div className={styles.flexBetween}><Image  width={20}  height={20}  src={'/img/'  + item.picCode}  preview={false} /> <span className={styles.topRight} ></span></div>

        <div style={{margin: '0 0 -2px 10px',color:'rgb(64 255 255)',    marginTop: '-3px'}}  className={styles.flex}><span>{item.fileds[0]?.abb}</span><div className={styles.dataBox} ><span className={styles.data1} >--</span>{item.unit}</div></div>
        <div className={styles.attribute}  >{item.text}</div>
      </div>);
        break;
   case 4:
          url = (
            <div key={key}   className={styles.dataItem}  data-grid={{...attrLayout[index], static: true}}>
               
            <div className={styles.flexBetween}>
              <Image width={20} height={20} src={'/img/'  + item.picCode} preview={false} />{' '}
              <span className={styles.topRight}></span>
            </div>
            <div>
            <div
             
              className={styles.flex}
            >
              <span>
                <span className={styles.nameItalic}>{item.fileds[0]?.abb}</span>
              </span>
              <div className={styles.dataBox}>
                <span className={styles.data1}>--</span>{item.unit}
              </div>
            </div>
            <div className={styles.flexcenter}>
            {item.fileds.map((filed ,filedindex) => (
             filedindex>0?
              <div className={styles.flexColumn}>
                <span className={styles.data2}>--</span>
                <span className={styles.attr} >{filed?.abb}</span>
              </div>
              :null
            
            ))}
              
            </div>
          </div>
          <div className={styles.attribute}>{item.text}</div>
        </div>
  );
          break;
        
          case 5:
            url = (
              <div   key={key}  className={styles.dataItem}  data-grid={{...attrLayout[index], static: true}}>
            
              <div className={styles.flexBetween}>
                <Image width={20} height={20} src={'/img/'  + item.picCode} preview={false} />{' '}
                <span className={styles.topRight}></span>
              </div>
              <div>
                <div className={styles.flexcenter1}>
                {item.fileds.map((filed ,filedindex) => (
               
                  <div className={styles.flexColumn}>
                    <span className={styles.data2}>--</span>
                    <span className={styles.attr} >{filed?.abb}</span>
                  </div>
                 
                
                ))}
                </div>
              </div>
              <div className={styles.attribute}>{item.text}</div>
            </div>
    );
            break;
           
             
    default:
      url = (
        <div  key={key} data-grid={{...attrLayout[index], static: true}}>
          <Card className={ styles.alarmBox}  >
        
          <div className={styles.title1}>{item.text}</div>
          <div className={styles.alrmcontent} >

        
            { alarmlist.map((item,index) => {
              if(alarmlist.length>12){
                if(index%2==0){
                  return( <div className={styles.flexBetween} >
                    <div style={{flex:1}} className={styles.flex}>
                      <div className={styles.yuan}  ></div>
                      <span className={styles.baojingText}>{item.alarmDes}</span>
                    </div>
                    {alarmlist.length%2==0||alarmlist.length-1>index? <div className={styles.flex} style={{flex:1}}>
                      <div className={styles.yuan}   ></div>
                      <span className={styles.baojingText}>{alarmlist[index+1].alarmDes}</span>
                    </div>:<div className={styles.flex} style={{flex:1}}></div>}
                  </div>)
                }
              }else{
                return  <div className={styles.flex} ><div className={styles.yuan}  ></div><span className={styles.baojingText}>{item.alarmDes}</span></div>
              }
             
            } )}
        </div>
        </Card>
        </div> 
      );
      break;
  }
  return url;
}


 



  return (
    <div className={styles.main} key={1}>
     
     <div  className={styles.flexBetween} style={{    marginRight: '10px',    alignItems: 'end'}}>
     <div className={styles.flexBetween} style={{flex:5,    alignItems: 'end'}}>
        <div style={{flex:  1}}> 
          <div  className={styles.flex}>  
            <Image    src={slg}  preview={false} />
            <div className={styles.deviceInfo} >
                <div>
                  <span  className={styles.title} > {deviceInfo?.deviceName||'--'} </span>
                  <span className={styles.updateTimeText} > (最新同步时间：{runningData?.acquisitionTime||'--'})</span>
                </div>
                <div className={styles.flexBetween} > 
                  <div>  
                    <span>设备位号：{deviceInfo?.deviceNo||'--'} </span>  
                    <span>&nbsp;  安装位置：{deviceInfo?.areaName||'--'}{deviceInfo?.devicePosition}</span>
                  </div>
                  <div>最新维保日期:{deviceInfo?.latestMaintenanceTime}</div>
                </div>  
            </div>
          </div>
          {/* <div>  
            <span>设备位号：{deviceInfo?.deviceNo||'--'} </span>  
            <span>&nbsp;  安装位置：{deviceInfo?.areaName||'--'}{deviceInfo?.devicePosition||'--'}</span>
          </div>         */}
        </div>
        {/* <div>最新维保日期:{deviceInfo?.latestMaintenanceTime}</div> */}
      </div>
      <div  className={styles.stateContent}>
          {designStateList.map((itemState,index) => (
            <div style={{display:"flex"}}>
            {itemState.map((item,index) => (
              <div  key={index+''} className={styles.state}  >
              <div  className={ [styles.yuan, item.color=='green'? styles.bgGreen: item.color=='red'? styles.bgRed:styles.bgYellow].join(' ')}></div>
              <span>{item.text}</span>
            </div>
            ))}
           </div>
             ))} 
      </div>
     </div>
     <div  className={styles.flexBetween} style={{    margin: '12px 0 30px 0',   position: 'relative'}} >
      <ResponsiveGridLayout  style={{    width:'100%'}}    rowHeight={28}  breakpoints={{lg: 1400, md: 996, sm: 768}} cols={{lg: 15, md: 15, sm: 15}} >
       {designAttrList.map((item,index) => (
            designItem(item,index)

          ))}
      </ResponsiveGridLayout>
</div>

      {/* <div  style={{flex:5}}>
        <div className={styles.flex} >
          <div  className={styles.dataItem}>
            <div className={styles.flexBetween}><Image  width={20}  height={20}  src={item1}  preview={false} /> <span className={styles.topRight} ></span></div>
            <div className={styles.middleValue}><span className={styles.data} >{runningData?.totalStart==null?"--":runningData?.totalStart}</span><span className={styles.unit}>次</span></div>
            <div className={styles.attribute}>总启动次数</div>
          </div>
          <div  className={styles.dataItem}>
            <div className={styles.flexBetween}><Image  width={20}  height={20}  src={item2}  preview={false} /> <span className={styles.topRight} ></span></div>
            <div  className={styles.middleValue}><span className={styles.data} >{runningData?.totalTrip==null?"--":runningData?.totalTrip}</span><span className={styles.unit}>次</span></div>
            <div className={styles.attribute}>总跳闸次数</div>
          </div>
          <div  className={styles.dataItem}>
            <div className={styles.flexBetween}><Image  width={20}  height={20}  src={item3}  preview={false} /> <span className={styles.topRight} >本次运行{runningData?.currentRuningHour==null?"--":runningData?.currentRuningHour}小时</span></div>
            <div className={styles.middleValue}><span className={styles.data} >{runningData?.totalRuningHour==null?"--":runningData?.totalRuningHour}</span><span className={styles.unit}>小时</span></div>
            <div className={styles.attribute}>累计运行时间</div>
          </div>
        </div>
        <div className={styles.flex} >
          <div  className={styles.dataItem}>
            <div className={styles.flexBetween}><Image  width={20}  height={20}  src={item4}  preview={false} /> <span className={styles.topRight} ></span></div>
            <div className={styles.middleValue}><span className={styles.data} >{runningData?.activePower==null?"--":runningData?.activePower}</span><span className={styles.unit}>kW</span></div>
            <div className={styles.attribute}>有功功率P</div>
          </div>
          <div  className={styles.dataItem}>
            <div className={styles.flexBetween}><Image  width={20}  height={20}  src={item5}  preview={false} /> <span className={styles.topRight} ></span></div>
            <div className={styles.middleValue}><span className={styles.data} >{runningData?.reactivePower==null?"--":runningData?.reactivePower}</span><span className={styles.unit}>kvar</span></div>
            <div className={styles.attribute}>无功功率Q</div>
          </div>
          <div  className={styles.dataItem}>
            <div className={styles.flexBetween}><Image  width={20}  height={20}  src={item6}  preview={false} /> <span className={styles.topRight} ></span></div>
            <div className={styles.middleValue}><span className={styles.data} >{runningData?.apparentPower==null?"--":runningData?.apparentPower}</span><span className={styles.unit}>kVA</span></div>
            <div className={styles.attribute}>视在功率S</div>
          </div>
        </div>
        <div className={styles.flex} >
        <div   style={{flex:1}}>
          <div  className={styles.dataItem} style={{height:'220px'}}>
            <div className={styles.flexBetween}><Image  width={20}  height={20}  src={item7}  preview={false} /> <span className={styles.topRight} >电流不平衡率
            {runningData?.currentUnbalance==null?"--":runningData?.currentUnbalance}%</span></div>
            <div> 
              <div style={{margin: '5px 0 -7px 10px',color:'rgb(64 255 255)'}}  className={styles.flex}><span><span  className={styles.nameItalic} >I</span>a</span><div className={styles.dataBox} ><span className={styles.data1} >{runningData?.phaseaCurrent==null?"--":runningData?.phaseaCurrent}</span>A</div></div>
              <div style={{margin: '0 0 -7px 10px',color:'rgb(64 255 255)'}}  className={styles.flex}><span><span  className={styles.nameItalic} >I</span>b</span><div className={styles.dataBox} ><span className={styles.data1} >{runningData?.phasebCurrent==null?"--":runningData?.phasebCurrent}</span>A</div></div>
              <div style={{margin: '0 0 -6px 10px',color:'rgb(64 255 255)'}}  className={styles.flex}><span><span  className={styles.nameItalic} >I</span>c</span><div className={styles.dataBox} ><span className={styles.data1} >{runningData?.phasecCurrent==null?"--":runningData?.phasecCurrent}</span>A</div></div>
            </div>
            <div className={styles.attribute} style={{marginTop:'10px'}}>三相电流</div>
          </div>
          </div>
          <div   style={{flex:1}}>
          <div  className={styles.dataItem} style={{height:'220px'}}>
            <div className={styles.flexBetween}><Image  width={20}  height={20}  src={item8}  preview={false} /> <span className={styles.topRight} ></span></div>
            <div> 
              <div style={{margin: '5px 0 -7px 10px',color:'rgb(64 255 255)'}}  className={styles.flex}><span ><span className={styles.nameItalic} >U</span>ab</span><div className={styles.dataBox} ><span className={styles.data1} >{runningData?.uabLineVoltage==null?"--":runningData?.uabLineVoltage}</span>V</div></div>
              <div style={{margin: '0 0 -7px 10px',color:'rgb(64 255 255)'}}   className={styles.flex}><span ><span className={styles.nameItalic}>U</span>bc</span><div className={styles.dataBox} ><span className={styles.data1} >{runningData?.ubcLineVoltage==null?"--":runningData?.ubcLineVoltage}</span>V</div></div>
              <div style={{margin: '0 0 -6px 10px',color:'rgb(64 255 255)'}}  className={styles.flex}><span ><span className={styles.nameItalic}>U</span>ac</span><div className={styles.dataBox} ><span className={styles.data1} >{runningData?.ucaLineVoltage==null?"--":runningData?.ucaLineVoltage}</span>V</div></div>
            </div>
            <div className={styles.attribute} style={{marginTop:'10px'}}>线电压</div>
          </div>
          </div>
          <div   style={{flex:1}}>
            <div  className={styles.dataItem}>
              <div className={styles.flexBetween}><Image  width={20}  height={20}  src={item91}  preview={false} /> <span className={styles.topRight} >{runningData?.powerFactor>=80?'高于':'低于'}80%</span></div>
              <div className={styles.middleValue}><span className={styles.data} >{runningData?.powerFactor==null?"--":runningData?.powerFactor}</span><span className={styles.unit}>%</span></div>
              <div className={styles.attribute}>功率因数cos</div>
            </div>
            <div  className={styles.dataItem} style={{marginTop:"10px"}}>
              <div className={styles.flexBetween}><Image  width={20}  height={20}  src={item92}  preview={false} /> <span className={styles.topRight} >{runningData?.heatCapacityPercentage>=80?'高于':'低于'}80%</span></div>
              <div className={styles.middleValue}><span className={styles.data} >{runningData?.heatCapacityPercentage==null?"--":runningData?.heatCapacityPercentage}</span><span className={styles.unit}>%</span></div>
              <div className={styles.attribute}>热容量百分比</div>
            </div>
          </div>
        </div>
    
      </div>
      <div className={styles.flex} style={{flex:3}}>
        <Card   className={ styles.alarmBox}  >
          <div className={styles.title1}>报警指示</div>
          <div className={styles.content} >
          {Object.keys(alarmcode).map((key ,index) => (
             <div className={styles.flex} ><div className={styles.yuan}   style={runningData?.alarmCode==key?{backgroundColor:alarmBackgroundColor}:{}}></div><span className={styles.baojingText}>{alarmcode[key]}报警</span></div>
            ))}
         </div>
        </Card>
        <Card    className={ styles.alarmBox}  >
        <div className={styles.title1}>跳闸指示</div>
        <div className={styles.content}>
          {Object.keys(alarmcode).map((key ,index) => (
             <div className={styles.flex} ><div className={styles.yuan}   style={runningData?.tripCode==key?{backgroundColor:tripBackgroundColor}:{}}></div><span className={styles.baojingText}>{alarmcode[key]}故障</span></div>
            ))}
         </div>
        </Card>
      </div>
      </div> */}
 
     
      <Row style={{marginRight: '0' }} key={6}>
   
        <div className={styles.tabsTitle}>
          {items.map((item,index) => (
          <>
            {index==0?  <> <a className={chartIndex!=0?styles.a1:[styles.a1,styles.tabcheck1].join(' ')}   onClick={()=>setChartIndex(index)} >三相电流趋势分析</a><div  className={chartIndex!=0?styles.a1after:[styles.a1after,styles.a1afterCheck].join(' ')}></div>   </>
            :index==items.length-1?
            <a className={chartIndex==index?[styles.a3,styles.tabcheck].join(' '):styles.a3}  onClick={()=>setChartIndex(index)}> 报警信息</a>
            : <a className={chartIndex==index?[styles.a2,styles.tabcheck].join(' '):styles.a2}   onClick={()=>setChartIndex(index)}> 三相电压趋势分析</a>
            }
          </> 
          ))}
        </div>
        <Card  className={ styles.modalItem} title={null} style={{width:"100%"}} >
          {items.map((item,index) => (
          item.label!="报警记录"?<ECharts  style={{display:chartIndex==index?'block':'none'}}   option={item.chartData} />:   <AlarmTable deviceId={params.id} display={chartIndex==index?'block':'none'} style={{display:chartIndex==index?'block':'none'}}></AlarmTable>
          ))}
 
         </Card>
       
      </Row>
    
       
    </div>
  );
};

export default details;